import { useEffect } from 'react'
import { AppLayout } from './components/Layout'
import { SettingsDialog } from './components/Settings'
import { useFileSystemStore } from './stores/fileSystemStore'
import { useTheme } from './hooks/useTheme'
import { useResponsiveLayout } from './hooks/useResponsiveLayout'
import { useSettings } from './hooks/useSettings'
import { ThemeProvider } from './components/theme/ThemeProvider'
import { LayoutProvider } from './components/layout/ResponsiveLayout'
import { ComponentRegistryContext, componentRegistry } from './components/registry/ComponentRegistry'
import { initializeStores } from './stores'
import { initializeComponentLibrary } from './components'
import { useAutoSync } from './stores/middleware/crossModuleSync'
import { apiServiceManager } from './services/api'
import './App.css'

// 应用初始化组件
function AppInitializer({ children }: { children: React.ReactNode }) {
  useAutoSync(); // 启用跨模块同步

  useEffect(() => {
    const initializeApp = async () => {
      try {
        // 初始化API服务
        await apiServiceManager.initialize();

        // 初始化状态管理
        await initializeStores();

        // 初始化组件库
        initializeComponentLibrary();

        console.log('✅ App initialized successfully');
      } catch (error) {
        console.error('❌ App initialization failed:', error);
      }
    };

    initializeApp();
  }, []);

  return <>{children}</>;
}

function App() {
  const { loadDirectory } = useFileSystemStore()

  // 主题管理
  useTheme()

  // 设置管理
  const {
    isSettingsDialogOpen,
    closeSettings,
  } = useSettings()

  // 响应式布局
  useResponsiveLayout()

  // 加载示例工作区
  const loadSampleWorkspace = async () => {
    try {
      // 使用项目根目录作为示例
      const samplePath = '.'  // 当前目录
      console.log('Loading workspace:', samplePath)
      await loadDirectory(samplePath)
      console.log('Workspace loaded successfully')
    } catch (err) {
      console.error('Failed to load sample workspace:', err)
      // 尝试备用路径
      try {
        const fallbackPath = process.cwd ? process.cwd() : '.'
        console.log('Trying fallback path:', fallbackPath)
        await loadDirectory(fallbackPath)
      } catch (fallbackErr) {
        console.error('Fallback also failed:', fallbackErr)
      }
    }
  }

  useEffect(() => {
    // 自动加载示例工作区
    loadSampleWorkspace()
  }, [])

  return (
    <ComponentRegistryContext.Provider value={componentRegistry}>
      <ThemeProvider>
        <LayoutProvider>
          <AppInitializer>
            <AppLayout>
              {/* 设置对话框 */}
              <SettingsDialog
                isOpen={isSettingsDialogOpen}
                onClose={closeSettings}
              />
            </AppLayout>
          </AppInitializer>
        </LayoutProvider>
      </ThemeProvider>
    </ComponentRegistryContext.Provider>
  )
}

export default App
